// server/renderer.js 渲染 react 组件
// 因为 Home 是 react 组件 所以还需要引入 react 来支持
import React from 'react'
import { renderToString } from 'react-dom/server'
// 路由组件 根据 location 来接收路由地址
import { StaticRouter } from 'react-router-dom'
// 路由规则
import routes from '../share/routes'
// 根据 StaticRouter 组件中的 location 路由地址来返回对应的组件
import { renderRoutes } from 'react-router-config'
import { Provider } from 'react-redux'
// 转换恶意代码
import serialize from 'serialize-javascript'

export default (req, store) => {
    // 将组件转换为字符串
    const content = renderToString(
        <Provider store={store}>
            <StaticRouter location={req.path}>
                { renderRoutes(routes) }
            </StaticRouter>
        </Provider>
    )
    // 获取初始状态 转换成字符串形式
    const initalState = serialize(store.getState())
    return `
    <html>
        <head>
            <title>React SSR</title>
        </head>
        <body>
            <div id="root">${content}</div>
            <script>window.INITIAL_STATE = ${initalState}</script>
            <script src="bundle.js"></script>
        </body>
    </html>
`
}